package router

import (
	"gin/controller"
	"gin/middleware"
	sessionsStore "gin/session"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	etcd "github.com/teamones-open/etcd-discovery"
	register_route "github.com/teamones-open/go-register-route"
)

func InitRouter() {
	router := gin.Default()

	// 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
	router.Use(middleware.Cors())

	// 使用 session(cookie-based)
	router.Use(sessions.Sessions("myyyyysession", sessionsStore.Store))

	router.GET("/", controller.HealthyReturn)

	auth := router.Group("auth")
	{
		// 获取IP
		auth.POST("/get_ip", controller.GetClientIp)
		// 生成token
		auth.POST("/generate_token", controller.GenerateToken)
		// 获取token
		auth.POST("/get_token", controller.GetToken)
	}

	log := router.Group("log")
	{
		log.POST("/add", controller.LogInsert)
		log.POST("/find", controller.LogFind)
		log.POST("/select", controller.LogSelect)
	}

	transactionRecords := router.Group("transaction_records")
	{
		transactionRecords.POST("/add", controller.WriteTransactionRecords)
	}

	monologRecords := router.Group("monolog")
	{
		monologRecords.POST("/add", controller.WriteMonologRecords)

		monologRecords.POST("/select", controller.SelectMonologRecords)
	}

	requestRecords := router.Group("request_log")
	{
		requestRecords.POST("/save", controller.WriteRequestRecords)
	}

	// 上报路由
	err := RegisterRoutes(router)
	if err != nil {
		logrus.Errorln(err.Error())
	}

	port := viper.GetString("server.port")
	if port != "" {

		// 注册服务到ETCD
		etcdStatus := viper.GetString("etcd.status")
		if etcdStatus == "active" {
			etcdHost := viper.GetString("etcd.host")
			etcdPort := viper.GetString("server.port")
			etcdServerName := viper.GetString("etcd.serverName")
			err := etcd.RegisterServer(etcdHost, etcdPort, etcdServerName)
			if err != nil {
				logrus.Errorln(err.Error())
			}
		}

		panic(router.Run(":" + port))
	}

	panic(router.Run())
}

// 路由上报注册
func RegisterRoutes(router *gin.Engine) (err error) {
	Routes := router.Routes()
	url := viper.GetString("rotueServer.url")
	serverName := viper.GetString("etcd.serverName")
	err = register_route.Register(Routes, url, serverName)
	return err
}
